package com.haierp.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.haierp.enums.ItemStatus;
import com.haierp.enums.LogisticType;
import com.haierp.exception.ErpCommonException;
import com.haierp.model.Category;
import com.haierp.model.Inventory;
import com.haierp.model.Item;
import com.haierp.model.ItemSku;
import com.haierp.service.ICategoryService;
import com.haierp.service.IInventoryService;
import com.haierp.service.IItemService;
import com.haierp.service.IItemSkuService;
import com.haierp.service.ISequenceUtilService;
import com.haierp.service.item.IOuterItemService;
import com.haierp.util.DateUtil;
import com.haierp.util.DimensionCodeUtil;
import com.haierp.util.EasyuiJsonResult;
import com.haierp.util.ImageUtil;
import com.haierp.util.JsonPageResult;
import com.haierp.util.JsonResult;
import com.haierp.util.PropertiesUtils;
import com.haierp.vo.ItemQueryVO;
import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.shiro.ShiroUser;
import com.wangzhixuan.commons.utils.HaiJsonUtils;
import com.wangzhixuan.commons.utils.StringUtils;

import net.sf.json.JSONObject;

/**
 * 商品处理器
 * 
 * @author zhulu
 *
 */
@Controller
@RequestMapping("/item")
public class ItemController extends BaseController {

	@Autowired
	private IItemService iItemService;
	
	@Autowired
	private IItemSkuService itemSkuService;
	
	@Autowired
	private ICategoryService categoryService;
	
	@Autowired
	private ISequenceUtilService sequenceUtilService;
	
	@Autowired
	private IOuterItemService outerItemService;
	
	@Autowired
	private IInventoryService inventoryService;
	
	public static final String getaccess_tokenurl = "https://api.weixin.qq.com/cgi-bin/token";
	public static final String getaccess_tokenparam = "grant_type=client_credential&appid="+PropertiesUtils.getProperties().getProperty("wx.sale.appId")+"&secret="+PropertiesUtils.getProperties().getProperty("wx.sale.appSecret");
	
	/**
	 * 添加商品
	 *
	 * @param
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Object add(Item item) {
		JsonResult<Item> result = new JsonResult<>();
		if (item.getId() == null) {
			ShiroUser shiroUser = this.getShiroUser();
			String itemCreater = shiroUser.getLoginName();
			StringBuffer nameNew = new StringBuffer();
			//品牌
			String[] brandArr = item.getBrand().split("->");
			if(StringUtil.isNotBlank(brandArr[0])) {	//英文品牌
				nameNew.append(brandArr[0] + " ");
			}
			if(brandArr.length>1 && StringUtil.isNotBlank(brandArr[1])) {	//中文品牌
				nameNew.append(brandArr[1] + " ");
			}
			if(StringUtil.isNotBlank(item.getSexStyle())) {		//男女款
				nameNew.append(item.getSexStyle() + " ");
			}
			nameNew.append(item.getName() + " ");
			if(item.getLogisticType() != null) {		//发货方式
				nameNew.append(LogisticType.of(item.getLogisticType()).getDescription());
			}
			//重新设置商品名称
			item.setName(nameNew.toString());
			item.setCompanyId(shiroUser.getCompanyId());//设置商品所属公司
			item.setGmtCreate(new Date());
			item.setGmtModify(new Date());
			item.setUserCreate(itemCreater);
			Category category = categoryService.selectById(item.getCategoryId());
			String categoryCode = Category.categoryCode.get(item.getCategoryId());
			if(category!=null && categoryCode!=null){
				item.setCategoryName(category.getName());
			}else{
				return result.buildMsg("没有找到类目").buildIsSuccess(false);
			}
			item.setItemCode("I" + categoryCode + "Q" + sequenceUtilService.gainItemSequence());
			// 解析skuList 数组对象
			String skuList = item.getSkuList();
			Double minPrice = null;
			Double maxPrice = null;
			if (StringUtils.isNotBlank(skuList)) {
				try {
					String s = skuList.replace("&quot;", "\"");
					List<ItemSku> skus = HaiJsonUtils.toBean(s, new TypeReference<List<ItemSku>>(){});
					Map<String, Integer> colorScaleMap = new HashMap<String, Integer>();
					int i = 0;
					if (skus != null && !skus.isEmpty()) {
						for(int j=0; j<skus.size(); j++) {
							ItemSku itemSku = skus.get(j);
							//颜色和尺寸不能都为空
							if(StringUtil.isBlank(itemSku.getColor()) && StringUtil.isBlank(itemSku.getScale())) {
								return result.buildMsg("颜色和尺寸不能都为空").buildIsSuccess(false);
							}
							if(itemSku.getVirtualInv()>0 || itemSku.getTotalAvailableInv()>0) {
								if(minPrice == null) {
									minPrice = itemSku.getSalePrice();
									maxPrice = itemSku.getSalePrice();
								} else {
									if(minPrice > itemSku.getSalePrice())  minPrice = itemSku.getSalePrice();
									if(maxPrice < itemSku.getSalePrice())  maxPrice = itemSku.getSalePrice();
								}
							}
							//判断颜色，尺寸是否冲突
							String colorScaleKey = "";
							if(itemSku.getColor() != null) {
								String color = itemSku.getColor().trim();
								colorScaleKey += color;
								itemSku.setColor(color);
							}
							if(itemSku.getScale() != null) {
								String scale = itemSku.getScale().trim();
								colorScaleKey += scale;
								itemSku.setScale(scale);
							}
							if(StringUtil.isBlank(colorScaleKey)) colorScaleKey = "none";
							if(colorScaleMap.get(colorScaleKey)!=null) {
								return result.buildMsg("SKU颜色尺码重复").buildIsSuccess(false);
							}
							colorScaleMap.put(colorScaleKey, 1);
							
							itemSku.setSkuCode("S" + item.getItemCode().substring(1) + String.format("%0"+4+"d", ++i));
							itemSku.setSkuStatus(0);
							itemSku.setLogisticType(item.getLogisticType());
							//itemSku.setBuySite(item.getBuySite());
							itemSku.setCompanyId(shiroUser.getCompanyId());//SKU加入所属公司
							itemSku.setGmtCreate(new Date());
							itemSku.setGmtModify(new Date());
							itemSku.setUserCreate(itemCreater); //加入SKU创建者
							String skuPic = ImageUtil.getImageUrl(itemSku.getSkuPic());
							itemSku.setSkuPic(skuPic);
							if(StringUtils.isNotBlank(itemSku.getPackageLevelId()) ){
							  List<Long> a =  HaiJsonUtils.toBean(itemSku.getPackageLevelId(), new TypeReference<List<Long>>(){});
							  itemSku.setPackageId(a.get(a.size()-1));
							}

							if(j==skus.size()-1 && minPrice == null) {
								minPrice = itemSku.getSalePrice();
								maxPrice = itemSku.getSalePrice();
							}
						}
						item.setItemSkus(skus);
					}
				} catch (Exception e) {
					e.printStackTrace();
					return result.buildMsg("解析SKU错误").buildIsSuccess(false);
				}
			}
			//商品价格区间
			if(minPrice.equals(maxPrice)) {
				item.setPriceRange(maxPrice.toString());
			}  else {
				item.setPriceRange(minPrice.toString() + "-" + maxPrice.toString());
			}
			String imgJson = ImageUtil.getImageUrl(item.getMainPic());
			item.setMainPic(imgJson);
			detailDecoder(item);
			//判断是否可售
			if(item.getStartDate()==null || item.getEndDate()==null) {
				item.setIsSale(0);
			} else if(DateUtil.belongCalendar(new Date(), item.getStartDate(), DateUtil.getDateByCalculate(item.getEndDate(), Calendar.DATE, 1))) {
				item.setIsSale(1);
			} else {
				item.setIsSale(0);
			}
			iItemService.addItem(item);
			
			//同步到有赞并上架(如花商品即companyId =1 才同步有赞)
			if(item.getIsSale()!=null && item.getIsSale()==1 && item.getCompanyId()==1) {
				try {
					outerItemService.synItemYouzan(item.getId());
				} catch(Exception e) {
					logger.error("商品添加时同步到有赞：", e);
				}
			}
			//同步生成小程序的二维码(先不对外开放小程序)
			if(item.getId()!= null && item.getCompanyId()==1) {
				voidDimensionCodeUtil(item.getId());
			}
			return result.buildIsSuccess(true);
		} else {
			return result.buildMsg("新增不能有ID").buildIsSuccess(false);
		}
	}

	/**
	 * 更新商品
	 *
	 * @param
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Object update(Item item) {
		JsonResult<Item> result = new JsonResult<>();
		// if haven't item id ,add item
		if (item.getId() == null) {
			return result.buildIsSuccess(false).buildMsg("没有Item id");
		} else {
			ShiroUser one = this.getShiroUser();
			StringBuffer nameNew = new StringBuffer();
			//品牌
			String[] brandArr = item.getBrand().split("->");
			if(StringUtil.isNotBlank(brandArr[0])) {	//英文品牌
				nameNew.append(brandArr[0] + " ");
			}
			if(brandArr.length>1 && StringUtil.isNotBlank(brandArr[1])) {	//中文品牌
				nameNew.append(brandArr[1] + " ");
			}
			if(StringUtil.isNotBlank(item.getSexStyle())) {		//男女款
				nameNew.append(item.getSexStyle() + " ");
			}
			nameNew.append(item.getName() + " ");
			if(item.getLogisticType() != null) {		//发货方式
				nameNew.append(LogisticType.of(item.getLogisticType()).getDescription());
			}
			//重新设置商品名称
			item.setName(nameNew.toString());
			item.setCompanyId(one.getCompanyId());//修改商品重置comoanyId
			Category category = categoryService.selectById(item.getCategoryId());
			if(category!=null){
				item.setCategoryName(category.getName());
			}else{
				return result.buildMsg("没有找到类目").buildIsSuccess(false);
			}
			item.setGmtModify(new Date());
			String skuList = item.getSkuList();
			Double minPrice = null;
			Double maxPrice = null;
			if (StringUtils.isNotBlank(skuList)) {
				Integer i = itemSkuService.queryMaxSkuCodeIndex(item.getId());
				if(i==null) i=0;
				
				try {
					String s = skuList.replace("&quot;", "\"");
					List<ItemSku> skus = HaiJsonUtils.toBean(s, new TypeReference<List<ItemSku>>(){});
					Map<String, Integer> colorScaleMap = new HashMap<String, Integer>();
					if (skus != null && !skus.isEmpty()) {
						for(int j=0; j<skus.size(); j++) {
							ItemSku itemSku = skus.get(j);
							//颜色和尺寸不能都为空
							if(StringUtil.isBlank(itemSku.getColor()) && StringUtil.isBlank(itemSku.getScale())) {
								return result.buildMsg("颜色和尺寸不能都为空").buildIsSuccess(false);
							}
							if(itemSku.getVirtualInv()>0 || itemSku.getTotalAvailableInv()>0) {
								if(minPrice == null) {
									minPrice = itemSku.getSalePrice();
									maxPrice = itemSku.getSalePrice();
								} else {
									if(minPrice > itemSku.getSalePrice())  minPrice = itemSku.getSalePrice();
									if(maxPrice < itemSku.getSalePrice())  maxPrice = itemSku.getSalePrice();
								}
							}
							//判断颜色，尺寸是否冲突
							String colorScaleKey = "";
							if(itemSku.getColor()!=null) {
								String color = itemSku.getColor().trim();
								colorScaleKey += color;
								itemSku.setColor(color);
							}
							if(itemSku.getScale()!=null) {
								String scale = itemSku.getScale().trim();
								colorScaleKey += scale;
								itemSku.setScale(scale);
							}
							if(StringUtil.isBlank(colorScaleKey)) colorScaleKey = "none";
							if(colorScaleMap.get(colorScaleKey)!=null) {
								return result.buildMsg("SKU颜色尺码重复").buildIsSuccess(false);
							}
							colorScaleMap.put(colorScaleKey, 1);
							
							if(itemSku.getId()==null){
								itemSku.setSkuCode("S" + item.getItemCode().substring(1) + String.format("%0"+4+"d", ++i));
								itemSku.setSkuStatus(0);
								itemSku.setUserCreate(one.getLoginName());
								itemSku.setGmtCreate(new Date());
								itemSku.setGmtModify(new Date());
							}
							itemSku.setLogisticType(item.getLogisticType());
							//itemSku.setBuySite(item.getBuySite());
							itemSku.setItemId(item.getId());
							itemSku.setCompanyId(item.getCompanyId());//update 商品同时companyId
							itemSku.setItemCode(item.getItemCode());
							itemSku.setItemName(item.getName());
							itemSku.setCategoryId(item.getCategoryId());
							itemSku.setCategoryName(item.getCategoryName());
							itemSku.setBrand(item.getBrand());
							String skuPic = ImageUtil.getImageUrl(itemSku.getSkuPic());
							itemSku.setSkuPic(skuPic);
							
							if(StringUtils.isNotBlank(itemSku.getPackageLevelId()) ){
								  List<Long> a =  HaiJsonUtils.toBean(itemSku.getPackageLevelId(), new TypeReference<List<Long>>(){});
								  itemSku.setPackageId(a.get(a.size()-1));
								}

							if(j==skus.size()-1 && minPrice == null) {
								minPrice = itemSku.getSalePrice();
								maxPrice = itemSku.getSalePrice();
							}
						}
						item.setItemSkus(skus);
					}
				} catch (Exception e) {
					e.printStackTrace();
					return result.buildMsg("解析SKU错误").buildIsSuccess(false);
				}
			}
			//商品价格区间
			if(minPrice.equals(maxPrice)) {
				item.setPriceRange(maxPrice.toString());
			}  else {
				item.setPriceRange(minPrice.toString() + "-" + maxPrice.toString());
			}
			String imgJson = ImageUtil.getImageUrl(item.getMainPic());
			item.setMainPic(imgJson);
			detailDecoder(item);
			//判断是否可售
			if(item.getStartDate()==null || item.getEndDate()==null) {
				item.setIsSale(0);
			} else if(DateUtil.belongCalendar(new Date(), item.getStartDate(), DateUtil.getDateByCalculate(item.getEndDate(), Calendar.DATE, 1))) {
				item.setIsSale(1);
			} else {
				item.setIsSale(0);
			}
			//编辑运费
			if(item.getFreight()==null) {
				item.setFreight(0.0d);
			}
			iItemService.updateItem(item);
			
			//同步到有赞 并且商品的所属Id为1，即如花的商品才同步有赞
			Item sysItem = iItemService.selectById(item.getId());
			try {
				if(sysItem.getCompanyId()==1){
					if(sysItem.getIsSale()!=null && sysItem.getIsSale()==1) {
						if(sysItem.getStatus()==ItemStatus.DELISTING.getCode()) {
							outerItemService.listingYouzan(sysItem);
						}
						outerItemService.synItemYouzan(sysItem.getId());
					} else {
						outerItemService.delistingYouzan(sysItem);
					}
				}

			} catch(Exception e) {
				logger.error("商品修改时同步到有赞：", e);
			}
			return result.buildIsSuccess(true);
		}
	}

	private void detailDecoder(Item item) {
		if(StringUtils.isNotBlank(item.getDetail())){
			String detail = item.getDetail();
			try {
				String deStr = URLDecoder.decode(detail, "UTF-8");
				item.setDetail(deStr);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
	}
	
	@RequestMapping("/query")
	@ResponseBody
	public Object query(ItemQueryVO itemQueryVO) {
		JsonResult<Item> result = new JsonResult<>();
		// if haven't item id ,add item
		if (itemQueryVO.getItemId() != null) {
			Item item = iItemService.queryItem(itemQueryVO);
			if (item == null) {
				result.buildIsSuccess(false).buildMsg("没有找到Item");
			}
			String itemName = item.getName();
			if(itemName.contains("婴儿款")) {
				item.setSexStyle("婴儿款");
			} else if(itemName.contains("大童男款")) {
				item.setSexStyle("大童男款");
			} else if(itemName.contains("大童女款")) {
				item.setSexStyle("大童女款");
			} else if(itemName.contains("小童男款")) {
				item.setSexStyle("小童男款");
			} else if(itemName.contains("小童女款")) {
				item.setSexStyle("小童女款");
			} else if(itemName.contains("男款")) {
				item.setSexStyle("男款");
			} else if(itemName.contains("女款")) {
				item.setSexStyle("女款");
			} else if(itemName.contains("大童款")) {
				item.setSexStyle("大童款");
			} else if(itemName.contains("小童款")) {
				item.setSexStyle("小童款");
			} else if(itemName.contains("儿童款")) {
				item.setSexStyle("儿童款");
			}
			
			StringBuffer nameRep = new StringBuffer();
			//品牌
			String[] brandArr = item.getBrand().split("->");
			if(StringUtil.isNotBlank(brandArr[0])) {	//英文品牌
				nameRep.append(brandArr[0] + " ");
			}
			if(brandArr.length>1 && StringUtil.isNotBlank(brandArr[1])) {	//中文品牌
				nameRep.append(brandArr[1] + " ");
			}
			if(StringUtil.isNotBlank(item.getSexStyle())) {		//男女款
				nameRep.append(item.getSexStyle() + " ");
			}
			//重新设置商品名称
			String itemNameTemp = itemName.replace(nameRep.toString(), "");
			String itemNameNew = null;
			if(item.getLogisticType() != null) {
				itemNameNew = itemNameTemp.replace(LogisticType.of(item.getLogisticType()).getDescription(),"");
			}
			item.setName(itemNameNew);			
			result.setData(item);
			return result.buildIsSuccess(true);
		} else {
			return result.buildIsSuccess(false).buildMsg("没有Item id");
		}
	}

	@RequestMapping("/queryItems")
	@ResponseBody
	public Object queryItems(ItemQueryVO itemQueryVO) {
		JsonPageResult<List<Item>> result = iItemService.queryItems(itemQueryVO);

		return result.buildIsSuccess(true);
	}
	
	@RequestMapping("/queryItemBuySite")
	@ResponseBody
	public Object queryItemBuySite(ItemQueryVO itemQueryVO) {
		JsonPageResult<List<Item>> result = iItemService.queryItemBuySite(itemQueryVO);
		return result.buildIsSuccess(true);
	}

	@RequestMapping("/queryItembuySiteNoPaging")
	@ResponseBody
	public Object queryItembuySiteNoPaging(ItemQueryVO itemQueryVO) {
		JsonResult<List<Item>> result = iItemService.queryItembuySiteNoPaging(itemQueryVO);
		return result.buildIsSuccess(true);
	}
	
	/**
	 * 商品批量上架
	 * @param itemIdStrs 要上架的商品ID集合 ，分隔符   123,222,132 
	 * @return
	 */
	@RequestMapping("/itemsListing")
	@ResponseBody
	public Object itemsListing(String itemIdStrs) {
		JsonResult<String> result = new JsonResult<>();
		//查询出商品，查看商品状态，新档或者下架的商品可以上架
		if(itemIdStrs!=null){
		String [] items = itemIdStrs.split(",");
		List<Long>  itemIds = new ArrayList<>();
			if(items!=null&&items.length>0){
			
				for (int i = 0;i<items.length;i++) {
					Long one = Long.valueOf(items[i]);
					itemIds.add(one);
				}
				List<Item> itemList = iItemService.queryItems(itemIds);
				//获取有赞的num_iid;
				
				//调取有赞批量上架接口
				
				
			}else{
				return result.buildIsSuccess(false);
			}
		}else{
			return result.buildIsSuccess(false);
		}
//		return result.buildIsSuccess(true);
		return result;
	}
	
	
	/**
	 * 商品批量发布到有赞
	 * @return
	 */
	@RequestMapping("/itemsPush")
	@ResponseBody
	public Object itemsPush(String itemIdStrs) {
		JsonResult<String> result = new JsonResult<>();
		//查询出商品，查看商品状态，新档或者下架的商品可以上架
		if(itemIdStrs!=null){
		String [] items = itemIdStrs.split(",");
		List<Long>  itemIds = new ArrayList<>();
			if(items!=null&&items.length>0){
			
				for (int i = 0;i<items.length;i++) {
					Long one = Long.valueOf(items[i]);
					itemIds.add(one);
				}
				List<Item> itemList = iItemService.queryItems(itemIds);
				//获取有赞的num_iid;
				
				//调取有赞批量上架接口
				
				
			}else{
				return result.buildIsSuccess(false);
			}
		}else{
			return result.buildIsSuccess(false);
		}
//		return result.buildIsSuccess(true);
		return result;
	}

	/**
	 * 商品查询管理主列表
	 *
	 * @return
	 */
	@RequestMapping("/queryItemList")
	@ResponseBody
	public Object queryItemList(ItemQueryVO itemQueryVO) {
		JsonPageResult<List<Item>> result = iItemService.queryItems(itemQueryVO);
		EasyuiJsonResult<List<Item>> jsonResult = new EasyuiJsonResult<>();
		jsonResult.setTotal(result.getTotalCount());
		jsonResult.setRows(result.getData());
		ShiroUser shiroUser = this.getShiroUser();
		Set<String> roles = shiroUser.getRoles();
		if(roles.contains("cgpm")){
			jsonResult.setProductRoler(true);
		}
		if(shiroUser.getCompanyId() == 2) {
			jsonResult.setSynproduct(true);
		}
		return jsonResult.buildIsSuccess(true);
	}
	
	@RequestMapping("/updateVirtualInvByItemId")
	@ResponseBody
	public Object updateVirtualInvByItemId(Long itemId){
		JsonResult<Item> result = new JsonResult<>();
		if(itemId!=null){
			inventoryService.updateVirtualInvByItemId(itemId);
		}		
		return result.buildIsSuccess(true);
	}
	/**
	 * 单品生成二维码
	 * @param itemId
	 * @return
	 */
	@RequestMapping("/getDimensionCodeUtil")
	@ResponseBody
	public Object getDimensionCodeUtil(Long itemId) {
		JsonResult<Object> result = new JsonResult<>();
		ShiroUser one = this.getShiroUser();
		if (one.getCompanyId() != 1) {
			throw new ErpCommonException("暂无权限执行此操作！");
		}
		String reponse = DimensionCodeUtil.sendGet(getaccess_tokenurl, getaccess_tokenparam);
		JSONObject myJson = JSONObject.fromObject(reponse);
		String token = (String) myJson.get("access_token");
		String picUrl = iItemService.insertIntoItemDimension(itemId.toString(), "pages/itemDetail/itemDetail", token);
		if (StringUtil.isNotBlank(picUrl)) {
			if (itemId != null) {
				ItemQueryVO itemQueryVO = new ItemQueryVO();
				itemQueryVO.setItemId(itemId);
				Item item = iItemService.queryItem(itemQueryVO);
				item.setDimensionCodePic(picUrl);
				iItemService.updateSelectiveById(item);
			}
		}
		return result.buildIsSuccess(true);
	}
	/**
	 * 新增商品同时生成二维码
	 * @param itemId
	 */
	private void voidDimensionCodeUtil(Long itemId) {
		String reponse = DimensionCodeUtil.sendGet(getaccess_tokenurl, getaccess_tokenparam);
		JSONObject myJson = JSONObject.fromObject(reponse);
		String token = (String) myJson.get("access_token");
		String picUrl = iItemService.insertIntoItemDimension(itemId.toString(), "pages/itemDetail/itemDetail", token);
		if (StringUtil.isNotBlank(picUrl)) {
			if (itemId != null) {
				ItemQueryVO itemQueryVO = new ItemQueryVO();
				itemQueryVO.setItemId(itemId);
				Item item = iItemService.queryItem(itemQueryVO);
				item.setDimensionCodePic(picUrl);
				iItemService.updateSelectiveById(item);
			}
		}
		
	}
	/**
	 * 删除重复商品
	 * @param fileManageId
	 * @return
	 */
	@RequestMapping("/deleteRepeatItem")
	@ResponseBody
	public Object deleteFile(Long itemId){
		JsonResult<String> result = new JsonResult<>();
		 Item one = iItemService.selectById(itemId);
		 if(one != null){
			 EntityWrapper<ItemSku>  entityWrapper = new EntityWrapper<ItemSku>();
			 entityWrapper.where("item_id={0}", one.getId());
			 List<ItemSku> skuList = itemSkuService.selectList(entityWrapper);
			 for (ItemSku itemSku : skuList) {
				 itemSkuService.deleteById(itemSku);
			}
			 EntityWrapper<Inventory> inventoryentityWrapper = new EntityWrapper<Inventory>();
			 inventoryentityWrapper.where("item_id={0}", one.getId());
			 List<Inventory>   listInventory = inventoryService.selectList(inventoryentityWrapper);
			 for (Inventory inventory : listInventory) {
				 inventoryService.deleteById(inventory);
			}
			 iItemService.deleteById(one);
		 }

		return result.buildIsSuccess(true);
	}
	/**
	 * 采购货源情况反馈销售
	 * @param itemQueryVO
	 * @return
	 */
	@RequestMapping("/responsePurchaseDetailToSaler")
	@ResponseBody
	public Object responsePurchaseDetailToSaler(ItemQueryVO itemQueryVO) {
		JsonPageResult<List<Item>> result = iItemService.responsePurchaseDetailToSaler(itemQueryVO);
		EasyuiJsonResult<List<Item>> jsonResult = new EasyuiJsonResult<>();
		jsonResult.setTotal(result.getTotalCount());
		jsonResult.setRows(result.getData());
		return jsonResult.buildIsSuccess(true);
	}
	
	/**
	 * 作废此商品
	 * 
	 * @param itemId
	 * @return
	 */
	@RequestMapping("/getcancelTheItem")
	@ResponseBody
	public Object getcancelTheItem(Long itemId) {
		JsonResult<Object> result = new JsonResult<>();
		ShiroUser one = this.getShiroUser();
		if (one.getCompanyId() != 1) {
			throw new ErpCommonException("暂无权限执行此操作！");
		}
		if (itemId != null) {
			ItemQueryVO itemQueryVO = new ItemQueryVO();
			itemQueryVO.setItemId(itemId);
			Item item = iItemService.queryItem(itemQueryVO);
			item.setStatus(-1);
			iItemService.updateSelectiveById(item);
			List<ItemSku> itemSkus = itemSkuService.queryItemSkusByItemId(itemQueryVO);
			for (ItemSku itemSku : itemSkus) {
				itemSku.setSkuStatus(-1);
				itemSkuService.updateSelectiveById(itemSku);
			}
		}
		return result.buildIsSuccess(true);
	}

}
